<template>
  <k-view class="stock-diagnosis">
    <confirm-dialog
      v-if="showNoDataDialog"
      title="提示"
      content="未查询到该公司的得分信息，请返回查看其他个股诊断"
      confirm-text="知道了"
      hide-cancel
      @success="dialogFn"
      @fail="dialogFn"
    ></confirm-dialog>
    <k-view class="header-view">
      <stock-diagnosis-card :stockInfo="stockInfo"></stock-diagnosis-card>
    </k-view>
    <k-view class="content-view">
      <k-view class="card-view card-view-header">
        <k-text class="content-title">{{ contentTitle }}</k-text>
        <k-text class="content-sub-title"
          >{{ changeStringIntoDate(companyOverview.report_date)
          }}{{ createReportQuarter(companyOverview.report_date) }}</k-text
        >
        <k-view class="rank-list-view">
          <k-view v-for="(item, index) in rankList" :key="index">
            <rank-card :cardInfo="item"></rank-card>
          </k-view>
        </k-view>
        <k-view class="radar-chart-view">
          <radar
            :themeType="'mobile-app-' + theme"
            :chartData="radarChartData"
            @radarClick="radarClick"
            :radarNum="formatChgString(companyOverview.composite_score, 2)"
            radarTxt="综合得分"
          ></radar>
        </k-view>
        <score-read
          v-if="companyOverview.composite_score_label"
          :stockInfo="stockInfo"
          :companyOverview="companyOverview"
        ></score-read>
        <knowledge-link></knowledge-link>
        <score-radio-tabs
          :modelValue="activeRadioTab"
          @change="handleRadioChange"
          :radioTabList="radioTabList"
        ></score-radio-tabs>
        <k-view v-if="activeRadioTab === 1">
          <bar
            :themeType="'mobile-app-' + theme"
            :chartData="barChartData"
            :showLabel="false"
            :yAxisMin="baryAxisMin"
            :yAxisMax="baryAxisMax"
          ></bar>
        </k-view>
        <k-view v-if="activeRadioTab === 2">
          <score-comparison
            :themeType="'mobile-app-' + theme"
            :stockInfo="stockInfo"
          ></score-comparison>
        </k-view>
      </k-view>
      <k-view class="card-view card-view-bottom">
        <PkIcon :stockCode="stockInfo.code" :stockName="stockInfo.name" />
        <k-text class="content-title">{{ contentDetailTitle }}</k-text>
        <stock-score-tabs
          :modelValue="activeScoreTab"
          @change="handleScoreTabChange"
          :riskArr="riskArr"
          class="score-tabs"
        ></stock-score-tabs>
        <score-diagnosis-read
          :scoreInfo="systemScoreInfo"
          :diagnosisInfo="diagnosisInfo"
          :modelValue="activeScoreTab"
          :theme="theme"
          :stockInfo="stockInfo"
          chartType="tag"
          class="score-read"
        ></score-diagnosis-read>
        <stock-diagnosis-table
          :tableData="tableData"
          :auth="auth"
          @hasClickBuy="hasClickBuy"
          :theme="theme"
        ></stock-diagnosis-table>
      </k-view>
    </k-view>
  </k-view>
</template>

<script>
import Apis from '@king-fisher/apis';
import RankCard from '@/components/StockDiagnosis/rankCard.vue';
import StockDiagnosisCard from '../../components/StockDiagnosis/stockCard.vue';
import ScoreRead from '@/components/StockDiagnosis/scoreRead.vue';
import KnowledgeLink from '@/components/StockDiagnosis/knowledgeLink.vue';
import StockScoreTabs from '@/components/StockDiagnosis/listTabs.vue';
import ScoreDiagnosisRead from '@/components/StockDiagnosis/scoreDiagnosis.vue';
import ScoreRadioTabs from '@/components/StockDiagnosis/radioTabs.vue';
import StockDiagnosisTable from '@/components/StockDiagnosis/diagnosisTable.vue';
import ConfirmDialog from '@/components/Intro/ConfirmDialog.vue';
import PkIcon from '@/components/Pk/pkIcon.vue';
import themeMixin from '../../mixins/themeMixin';
import fl from '@king-fisher/falcon';
import {
  changeStringIntoDate,
  formatChgStringScore,
  formatChgString,
  formatChgStringColor,
  getDateQuarter,
  getUrlSearch,
  navigateBack,
  setCookie,
  previousPeriod,
} from '@/utils/index';

import { getCompanyOverview, getStockHistory, getStockScore } from '@/apis/index';
import { scoreDetailList, SYSTEM } from '@/scripts/scoreDetail';
import ScoreComparison from '@/components/StockDiagnosis/scoreComparison.vue';
import { sendClickStat, sendPageStat } from '@/utils/stat';
import { PAGEID } from '@/config/stat';

const chartHeaderData = [
  {
    name: '内部控制',
    max: 100,
  },
  {
    name: '企业文化',
    max: 100,
  },
  {
    name: '资产结构',
    max: 100,
  },
  {
    name: '法人治理',
    max: 100,
  },
  {
    name: '价值再造',
    max: 100,
  },
  {
    name: '竞争态势',
    max: 100,
  },
  {
    name: '产品销售',
    max: 100,
  },
  {
    name: '创利能力',
    max: 100,
  },
  {
    name: '外部监督',
    max: 100,
  },
];

const defaultOverViewInfo = {
  composite_score: 0,
  urinary: {
    score: 0,
    num: 0,
  },
  immune: {
    score: 0,
    num: 0,
  },
  motor: {
    score: 0,
    num: 0,
  },
  respiratory: {
    score: 0,
    num: 0,
  },
  circulatory: {
    score: 0,
    num: 0,
  },
  market_rank: 0,
  composite_score_label: '基本面优秀',
  industry_rank_inc: 0,
  secretion: {
    score: 0,
    num: 0,
  },
  company_num: 0,
  market_rank_inc: 0,
  nervous: {
    score: 0,
    num: 0,
  },
  digesive: {
    score: 0,
    num: 0,
  },
  reproductive: {
    score: 0,
    num: 0,
  },
  score_inc: 0,
  industry_rank: 0,
  report_date: '20220930',
};

const defaultSingleSysSore = {
  company_num: 0,
  high_score_num: 0,
  higher_avg_num: 0,
  higher_avg_rate: 0,
  highest_score: 0,
  market_company_num: 0,
  market_score_avg: 0,
  minimum_score: 0,
  report_date: '20220930',
  score_avg: 0,
  score_inc: 0,
  score_inc_rate: 0,
};

export default {
  components: {
    StockDiagnosisCard,
    RankCard,
    ScoreRead,
    KnowledgeLink,
    StockScoreTabs,
    ScoreDiagnosisRead,
    ScoreRadioTabs,
    StockDiagnosisTable,
    ScoreComparison,
    ConfirmDialog,
    PkIcon,
  },
  data() {
    return {
      showNoDataDialog: false,
      titleText: '个股健康度诊断',
      contentTitle: '公司综合得分',
      contentDetailTitle: '得分明细',
      rankList: [],
      activeRadioTab: 1,
      activeScoreTab: 1,
      companyOverview: defaultOverViewInfo,
      radarChartData: {
        x: chartHeaderData,
        y: {
          y1: [0, 0, 0, 0, 0, 0, 0, 0, 0],
        },
      },
      barChartData: {
        x: [],
        y: {
          历史得分: [],
        },
      },
      stockInfo: {
        market: '',
        code: '',
        score: '',
        name: '',
      },
      currentSystemInfo: {
        id: 1,
        name: SYSTEM.nervous_score,
        key: 'nervous_score',
        content:
          '法人治理指数主要参考以下方面：党的领导、股东治理、董事会治理、管理层治理、监事会治理、信息披露。',
        index: 1,
      },
      tableData: [],
      systemScoreInfo: defaultSingleSysSore,
      diagnosisInfo: {
        scoreTitle: '系统得分',
        readArtical: '',
      },
      baryAxisMin: '0',
      baryAxisMax: '100',
      radioTabList: [
        {
          name: '历史得分',
          index: 1,
        },
        {
          name: '行业内对比',
          index: 2,
        },
      ],
      auth: 0,
      riskArr: [],
    };
  },
  mixins: [themeMixin],
  methods: {
    changeStringIntoDate,
    formatChgString,
    radarClick() {
      sendClickStat(`${PAGEID.STOCK}.radar.click`);
    },
    handleRadioChange(current) {
      // 只有此处才是点击切换页面tab
      if (this.activeRadioTab === current) {
        return;
      } else if (current === 1) {
        sendClickStat(`${PAGEID.STOCK}.tab.history.click`);
        this.activeRadioTab = current;
      } else {
        sendClickStat(`${PAGEID.STOCK}.tab.field.click`);
        this.activeRadioTab = current;
      }
    },
    handleScoreTabChange(current) {
      if (this.activeScoreTab === current) {
        return;
      } else {
        sendClickStat(`${PAGEID.STOCK}.system.${current}.click`);
        this.activeScoreTab = current;
        const resObj = scoreDetailList.find(item => item.id + '' === current + '');
        if (resObj) {
          this.currentSystemInfo = resObj;
          this.getStockScoreInfo();
        }
      }
    },
    async getStockScoreInfo() {
      const res = await getStockScore(this.stockInfo.code, this.currentSystemInfo.key);
      if (res.status_code !== 0) {
        Apis.Toast.show('暂未查询到相关信息');
        return;
      }
      this.systemScoreInfo.score_avg = formatChgString(res.data.score, 2);
      this.systemScoreInfo.score_inc_rate = res.data.score_rate;
      this.systemScoreInfo.market_score_avg = res.data.score_avg;
      this.diagnosisInfo.readArtical = res.data.label;
      this.tableData = res.data.index2_list;
      this.auth = res.data.auth || 0;
    },
    async getCompanyOverviewInfo() {
      const res = await getCompanyOverview(this.stockInfo.code);
      if (res.status_code !== 0) {
        Apis.Toast.show('暂未查询到相关信息');
        return;
      }
      if (!res.data) {
        this.showNoDataDialog = true;
        return;
      }
      this.companyOverview = res.data || defaultOverViewInfo;
      const rankData = this.createRankData(this.companyOverview);
      const radarData = this.createChartData(this.companyOverview);
      this.getRiskArr(this.companyOverview);
      this.rankList = rankData;
      this.radarChartData = radarData;
      this.stockInfo.score = this.companyOverview.composite_score?.toFixed(2);
    },
    getRiskArr(info) {
      const scoreDetailListKey = [
        'immune',
        'secretion',
        'motor',
        'nervous',
        'reproductive',
        'digesive',
        'urinary',
        'circulatory',
        'respiratory',
      ];
      Object.keys(info).forEach(key => {
        if (scoreDetailListKey.includes(key)) {
          const tempObj = {
            key: `${key}_score`,
            num: info[key]?.num || 0,
          };
          this.riskArr.push(tempObj);
        }
      });
    },
    createChartData(info) {
      const listData = [
        (info.immune?.score || 0).toFixed(2),
        (info.secretion?.score || 0).toFixed(2),
        (info.motor?.score || 0).toFixed(2),
        (info.nervous?.score || 0).toFixed(2),
        (info.reproductive?.score || 0).toFixed(2),
        (info.digesive?.score || 0).toFixed(2),
        (info.urinary?.score || 0).toFixed(2),
        (info.circulatory?.score || 0).toFixed(2),
        (info.respiratory?.score || 0).toFixed(2),
      ];
      return {
        x: chartHeaderData,
        y: {
          y1: listData,
        },
      };
    },
    createRankData(info) {
      const listData = [];
      listData.push({
        title: '公司综合得分',
        info: formatChgString(info.composite_score || 0, 2),
        subInfo: {
          name: previousPeriod,
          score: formatChgStringScore(info.score_inc, 2),
          color: formatChgStringColor(info.score_inc),
        },
      });
      listData.push({
        title: '全市场排名',
        info: `${formatChgString(info.market_rank)}/${formatChgString(info.company_num)}`,
        subInfo: {
          name: previousPeriod,
          score: formatChgStringScore(info.market_rank_inc),
          color: formatChgStringColor(info.market_rank_inc),
        },
      });
      listData.push({
        title: '行业内排名',
        info: `${formatChgString(info.industry_stock_rank)}/${formatChgString(info.industry_stock_num)}`,
        subInfo: {
          name: previousPeriod,
          score: formatChgStringScore(info.industry_stock_rank_inc, 1),
          color: formatChgStringColor(info.industry_stock_rank_inc),
        },
      });
      return listData;
    },
    async getCompanyHistoryInfo() {
      const res = await getStockHistory(this.stockInfo.code);
      if (res.status_code !== 0) {
        Apis.Toast.show('暂未查询到相关信息');
        return;
      }
      const barData = this.createBarData(res.data);
      this.barChartData = barData;
    },
    createBarData(info) {
      if (!info.score_list) {
        return {
          x: [],
          y: {
            历史得分: [],
          },
        };
      } else {
        // 获取近12个月的数据
        const resData = info.score_list?.slice(-6);
        this.baryAxisMax = this.findMaxScoreItem(resData).toFixed();
        this.baryAxisMin = this.findMinScoreItem(resData).toFixed();
        const barChartData = {
          x: resData.map(item => item.report_date),
          y: {
            历史得分: resData.map(item => item.score.toFixed(2)),
          },
        };
        return barChartData;
      }
    },
    findMaxScoreItem(list) {
      let result = 0;
      list.forEach(item => {
        if (item.score >= result) {
          result = item.score;
        }
      });
      return result + 1;
    },
    findMinScoreItem(list) {
      let result = 100;
      list.forEach(item => {
        if (item.score <= result) {
          result = item.score;
        }
      });
      return result - 2;
    },
    dialogFn() {
      navigateBack();
      this.showNoDataDialog = false;
    },
    createReportQuarter(str) {
      const qstr = getDateQuarter(str);
      return `根据${changeStringIntoDate(str, -1)}年Q${qstr}报告得出`;
    },
    hasClickBuy() {
      fl.onAppear(() => {
        this.getStockScoreInfo();
      });
    },
  },
  created() {
    const query = getUrlSearch();
    if (query && query.stockCode && query.market) {
      this.stockInfo.code = query.stockCode;
      this.stockInfo.market = query.market;
      const name = query.stockName || '';
      this.stockInfo.name = decodeURIComponent(name);
      this.getCompanyOverviewInfo();
      this.getStockScoreInfo();
      this.getCompanyHistoryInfo();
    }
  },
  mounted() {
    setCookie().then(id => {
      sessionStorage.setItem('userIdKey', id);
      sendPageStat(`${PAGEID.STOCK}.${this.stockInfo.code}`);
    });
  },
};
</script>

<style lang="less">
@paddingVal: 20px;

.stock-diagnosis {
  width: 100%;
  height: 100%;

  .header-view {
    background-color: #ff2436;
    padding: 20px 0 24px;
  }

  .content-view {
    width: 100%;
    height: 100%;
    background-color: #f5f5f5;
    padding: 16px 0;

    .card-view {
      position: relative;
      width: calc(100vw - 24px);
      box-sizing: border-box;
      margin: 0 auto 16px;
      background-color: #ffffff;
      border-radius: 16px;

      &-header {
        padding: @paddingVal;
      }

      &-bottom {
        padding-top: @paddingVal;
        .content-title {
          padding-left: @paddingVal;
        }

        .score-tabs {
          padding-left: @paddingVal;
        }

        .score-read {
          margin-left: @paddingVal;
          margin-right: @paddingVal;
        }
      }

      .content-title {
        font-size: 36px;
        color: #262626;
        font-weight: 500;
      }

      .content-sub-title {
        font-size: 24px;
        color: rgba(0, 0, 0, 0.4);
        font-weight: 400;
      }

      .rank-list-view {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        margin-top: 28px;
      }

      .radar-chart-view {
        margin: 28px 0;
      }
    }
  }
}

[theme-mode='black'] {
  .stock-diagnosis {
    .content-view {
      background: #0f0f0f;

      .card-view {
        background: #1c1c1c;

        .content-title {
          color: rgba(255, 255, 255, 0.84);
        }

        .content-sub-title {
          color: rgba(255, 255, 255, 0.6);
        }
      }
    }
  }
}
</style>
